package com.ellecity06.cwhiskymall.view.dialog

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseDialog
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.bean.response.AppVersionResponse
import com.ellecity06.cwhiskymall.databinding.DialogVersionUpdateBinding
import com.ellecity06.cwhiskymall.helper.DownloadManager
import java.io.File

/**
 * @author ellecity06
 * @time 2024/11/1 11:57
 * @des
 */
sealed class DownloadState {
    data class InProgress(val progress: Int) : DownloadState()
    data class Success(val file: File) : DownloadState()
    data class Error(val throwable: Throwable) : DownloadState()
}

class VersionUpdateDialog(
    private val activity: FragmentActivity,
    val data: AppVersionResponse
) :
    BaseDialog<DialogVersionUpdateBinding>(activity), View.OnClickListener {
    override val widthP: Float
        get() = 0.8F
    override val isCancelable: Boolean
        get() = false
    override val isTouchOutsideDismiss: Boolean
        get() = false
    private val file: File by lazy { File(activity.filesDir, "jiudage.apk") }
    override fun inflaterViewBinding(): DialogVersionUpdateBinding {
        return DialogVersionUpdateBinding.inflate(LayoutInflater.from(activity))
    }

    override fun initialize() {
        binding.tvNoUpdate.visibility = if (data.isForcedUpdate == 1) View.GONE else View.VISIBLE
        binding.tvDgVerTitle.text = "发现新版本V${data.versionNoShow}"
        binding.tvDgVerContent.text = data.content
        binding.tvNoUpdate.setOnClickListener(this)
        binding.tvDgVerConfirm.setOnClickListener(this)
//        LiveEventBus.get<Boolean>(BusConstants.NET_EVENT).observe(activity) {
//            if (it && downloadState != null && downloadState is DownloadState.Error) {
//                // 下载错误的时候收到网络恢复
//                logD("收到网络变化的通知了=$it，，开始下载")
//                downLoad()
//            }
//        }
    }

    private var downComplete: Boolean = false
    override fun onClick(view: View?) {
        when (view?.id) {
            binding.tvNoUpdate.id -> {
                dismiss()
            }
            binding.tvDgVerConfirm.id -> {
                if (downComplete) {
                    jumpInstall()
                } else {
                    downLoad()
                }

            }
        }
    }
private var downloadState:DownloadState? =null
    private fun downLoad() {
        if (data.url == null) return
        showProgress(0)
        downComplete
        activity.lifecycleScope.launchWhenCreated {
            DownloadManager.download(
                data.url!!,
                file
            ).collect {
                downloadState = it
                when (it) {
                    is DownloadState.InProgress -> {
                        Log.d("~~~", "download in progress: ${it.progress}.")
                        showProgress(it.progress)
                    }
                    is DownloadState.Success -> {
                        binding.tvDgVerConfirm.isEnabled = true
                        binding.tvDgVerConfirm.text = "安装新版"
                        downComplete = true
                        // 下载完成自动安装
                        jumpInstall()
                    }
                    is DownloadState.Error -> {
                        binding.pbDgDown.visibility = View.VISIBLE
                        binding.pbDgDown.progress = 0
                        binding.tvDgVerConfirm.isEnabled = true
                        binding.tvDgVerConfirm.text = "失败，请重试"
                    }
                }
            }
        }


    }

    private fun showProgress(progress: Int) {
        binding.pbDgDown.visibility = View.VISIBLE
        binding.pbDgDown.progress = progress
        binding.tvDgVerConfirm.isEnabled = false
        binding.tvDgVerConfirm.text = "${progress}%"
    }

    private fun jumpInstall() {
        try {
            val intent = Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            val uri: Uri = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                FileProvider.getUriForFile(activity, activity.packageName + ".fileProvider", file)
            } else {
                Uri.fromFile(file)
            }
            activity.startActivity(
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
            )
        } catch (e: Exception) {
            logD("安装异常=${file.absolutePath}", tr = e)
        }
    }

}